package com.example.bm.generator.controller;

import cn.hutool.core.date.DateUtil;
import com.example.bm.common.helper.GeneratorHelper;
import com.example.bm.generator.pojo.Column;
import com.example.bm.generator.pojo.Table;
import com.example.bm.generator.service.IGeneratorConfigService;
import com.example.common.constant.GeneratorConstant;
import com.example.common.domain.Layui;
import com.example.common.exception.ServiceException;
import com.example.common.util.StringUtil;
import com.example.dao.model.TGeneratorConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author bryceM
 */
@Slf4j
@RestController
@RequestMapping("generator/")
public class GeneratorController {

    @Autowired
    private IGeneratorConfigService generatorConfigService;
    @Autowired
    private GeneratorHelper generatorHelper;

    /**
     * 首页
     *
     * @param modelAndView
     * @return
     */
    @GetMapping(value = "/index")
    public ModelAndView index(ModelAndView modelAndView) {
        modelAndView.setViewName("views/generator/generate");
        return modelAndView;
    }


    @RequestMapping("/list")
    @ResponseBody
    public Layui<List<Table>> tablesInfo(@RequestParam Map<String, String> params, HttpServletRequest request) {
        try {
            int pageNum = Integer.parseInt(params.get("page"));
            int pageSize = Integer.parseInt(params.get("limit"));
            List<Table> tables = generatorConfigService.getTables(params, pageNum, pageSize);
            return Layui.success(tables);
        } catch (ServiceException e) {
            log.info(e.getMessage());
            return Layui.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Layui.error();
    }

    /**
     * 配置详情
     *
     * @return
     */
    @PostMapping("/config/detail")
    @ResponseBody
    public Layui<TGeneratorConfig> detail() {
        TGeneratorConfig bean = generatorConfigService.findGeneratorConfig();
        return Layui.success(bean);
    }

    /**
     * 更新配置
     *
     * @param generatorConfig
     * @return
     */
    @PostMapping("/config/update")
    @ResponseBody
    public Layui updateGeneratorConfig(TGeneratorConfig generatorConfig) {
        this.generatorConfigService.updateGeneratorConfig(generatorConfig);
        return Layui.success();
    }

    /**
     * 生成配置
     * @param params
     * @param remark
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping("/gen")
    @ResponseBody
    public Layui generate(@RequestParam Map<String, String> params, String remark, HttpServletResponse response) throws Exception {
        log.info("生成代码 params={}", params);
        String tableName = params.get("name");
        TGeneratorConfig generatorConfig = generatorConfigService.findGeneratorConfig();
        generatorConfig.setDate(DateUtil.formatDate(new Date()));
        if (generatorConfig.getId() == null) {
            return Layui.error("生成配置为空");
        }

        if (GeneratorConstant.TRIM_YES.equals(generatorConfig.getIsTrim())) {
            tableName = RegExUtils.replaceFirst(tableName, generatorConfig.getTrimValue(), StringUtils.EMPTY);
        }

        generatorConfig.setTableName(tableName);
        generatorConfig.setClassName(StringUtil.underscoreToCamel(tableName));
        generatorConfig.setTableComment(remark);

        //设置文件路径
        String prefix = generatorHelper.genPrefixPath(generatorConfig);
        generatorConfig.setGenPath(prefix);
        try {
            // 获取字段名
            List<Column> columns = generatorConfigService.getColumns(tableName);
            generatorHelper.generateEntityFile(columns, generatorConfig);
            generatorHelper.generateMapperFile(columns, generatorConfig);
            generatorHelper.generateMapperXmlFile(columns, generatorConfig);
            generatorHelper.generateServiceFile(columns, generatorConfig);
            generatorHelper.generateServiceImplFile(columns, generatorConfig);
            generatorHelper.generateControllerFile(columns, generatorConfig);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Layui.error();
        }
        return Layui.success(prefix);

        // 打包
        //String zipFile = System.currentTimeMillis() + SUFFIX;
        //FileUtil.compress(GeneratorConstant.TEMP_PATH + "src", zipFile);
        // 下载
        //FileUtil.download(zipFile, className + SUFFIX, true, response);
        // 删除临时目录
        //FileUtil.delete(GeneratorConstant.TEMP_PATH);
    }
}
